<template>
  <div class="product-page">
    <!-- 搜索表单 -->
<!--    <el-form :inline="true" :model="queryParams" class="search-form">-->
<!--      <el-form-item label="商品名称">-->
<!--        <el-input v-model="queryParams.name" placeholder="请输入商品名称"></el-input>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="handleQuery">查询</el-button>-->
<!--        <el-button @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <div class="product-list">
      <div class="product-item" v-for="item in productList" :key="item.id">
        <img :src="item.imageUrl" alt="product image" class="product-image"/>
        <div class="product-info">
          <h2 class="product-name">{{ item.name }}</h2>
          <p class="product-description">{{ item.description }}</p>
          <p>所需积分: {{ item.pointsRequired }}</p>
          <p>库存: {{ item.stock }}</p>
          <!-- 售空标识 -->
          <el-tag v-if="item.status === 3" type="danger" class="sold-out-tag">售空</el-tag>
          <div class="product-actions">
            <el-button size="mini" @click="handleRedeem(item)" :disabled="item.status === 3">兑换</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="queryParams.pageNum"
      :page-size="queryParams.pageSize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getList">
    </el-pagination>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <!-- 表单项 -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 兑换确认对话框 -->
    <el-dialog title="确认兑换" :visible.sync="redeemDialogVisible" width="30%">
      <span>您确定要兑换商品 "{{ currentProduct.name }}" 吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="redeemDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRedeem">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, redeemProduct } from "@/api/product/product";

export default {
  name: "Product",
  data() {
    return {
      contentDialogVisible: false, // 控制对话框显示/隐藏
      currentContent: '', // 当前要显示的富文本内容
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      productList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        description: null,
        pointsRequired: null,
        stock: null,
        imageUrl: null,
        status: null,
      },
      form: {},
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        pointsRequired: [
          { required: true, message: "兑换所需积分不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "商品状态不能为空", trigger: "change" }
        ],
      },
      redeemDialogVisible: false, // 控制兑换确认对话框显示/隐藏
      currentProduct: {} // 当前选择的商品信息
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 显示公告内容 */
    showContent(content) {
      this.currentContent = content;
      this.contentDialogVisible = true;
    },
    /** 查询商品后台管理列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        // 过滤掉状态为 2（下架）的商品
        this.productList = response.rows.filter(item => item.status !== 2);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        description: null,
        pointsRequired: null,
        stock: null,
        imageUrl: null,
        status: null,
        createTime: null,
        updateTime: null
      };
      this.$refs['form'].resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        description: null,
        pointsRequired: null,
        stock: null,
        imageUrl: null,
        status: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(`是否确认删除商品编号为"${ids}"的数据项？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delProduct(ids).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      }).catch(() => {});
    },
    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    /** 兑换按钮操作 */
    handleRedeem(item) {
      if (item.status === 3) {
        this.$message.warning("该商品已售空，无法兑换");
        return;
      }
      this.currentProduct = item;
      this.redeemDialogVisible = true;
    },
    /** 确认兑换 */
    confirmRedeem() {
      redeemProduct(this.currentProduct.id).then(response => {
        this.$message.success("兑换成功");
        this.redeemDialogVisible = false;
        this.getList(); // 更新商品列表
      }).catch(error => {
        this.$message.error("兑换失败：" + error.message);
      });
    }
  }
};
</script>


<style scoped>
.product-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-form {
  margin-bottom: 20px;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-list {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 20px; /* 商品之间的间距 */
  margin-top: 20px;
}

.product-item {
  border: 1px solid #e5e5e5;
  padding: 16px;
  width: calc(33.333% - 20px); /* 三列布局，减去间距 */
  box-sizing: border-box; /* 确保宽度包含 padding 和 border */
  text-align: center;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative; /* 为按钮定位提供参考 */
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.product-image {
  max-width: 100%;
  height: auto;
  margin-bottom: 10px;
  border-radius: 8px;
}

.product-info {
  text-align: left;
}

.product-name {
  font-size: 18px;
  color: #333;
  margin-bottom: 5px;
  font-weight: bold;
}

.sold-out-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 14px;
  font-weight: bold;
  padding: 5px 10px;
  background-color: #ff4d4f;
  color: #ffffff;
  border-radius: 4px;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  line-height: 1.5;
}

.product-actions {
  margin-top: 10px;
}

.el-button {
  border-radius: 4px;
  font-weight: bold;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  transition: background-color 0.3s ease;
  color: #ffffff; /* 白色文字 */
  font-weight: bold; /* 加粗 */
  padding: 10px 20px; /* 增大按钮大小 */
  font-size: 14px; /* 增大字体 */
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #409eff;
  color: #ffffff;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.el-dialog__title {
  color: #ffffff;
}

.el-dialog__footer {
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-input, .el-select, .el-textarea {
  width: 100%;
}

.el-input-number {
  width: 100%;
}

.el-input-number__decrease, .el-input-number__increase {
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-input-number__decrease:hover, .el-input-number__increase:hover {
  background-color: #e6e9ed;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px 20px;
  text-align: right;
}

.el-dialog__footer .el-button {
  margin-left: 10px;
}

.el-dialog__footer .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-dialog__footer .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-dialog__footer .el-button--default {
  background-color: #f5f7fa;
  border-color: #f5f7fa;
}

.el-dialog__footer .el-button--default:hover {
  background-color: #e6e9ed;
  border-color: #e6e9ed;
}
</style>
